package com.farm.service;

import java.math.BigDecimal;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.farm.entity.User;
import com.farm.entity.UserRole;
import com.farm.repository.UserRepository;

@Service
public class UserService implements UserDetailsService {
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.debug("Loading user by username: {}", username);
        return userRepository.findByUsername(username)
                .orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));
    }

    @Transactional
    public User registerUser(User user) {
        logger.info("Starting user registration for username: {}", user.getUsername());
        
        if (userRepository.findByUsername(user.getUsername()).isPresent()) {
            logger.warn("Username already exists: {}", user.getUsername());
            throw new RuntimeException("用户名已存在");
        }

        try {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            if (user.getRole() == UserRole.ADMIN) {
                user.setApproved(true);
            }
            User savedUser = userRepository.save(user);
            logger.info("Successfully registered user: {}", user.getUsername());
            return savedUser;
        } catch (Exception e) {
            logger.error("Error during user registration: {}", user.getUsername(), e);
            throw new RuntimeException("注册失败：" + e.getMessage());
        }
    }

    @Transactional
    public User approveUser(Long userId) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found"));
        user.setApproved(true);
        return userRepository.save(user);
    }

    @Transactional
    public User rechargeBalance(Long userId, BigDecimal amount) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found"));
        user.setBalance(user.getBalance().add(amount));
        return userRepository.save(user);
    }

    @Transactional
    public void rechargeAllEmployees(BigDecimal amount) {
        List<User> employees = userRepository.findByRole(UserRole.EMPLOYEE);
        for (User employee : employees) {
            employee.setBalance(employee.getBalance().add(amount));
            userRepository.save(employee);
        }
    }

    @Transactional
    public User updateUser(User user) {
        User existingUser = userRepository.findById(user.getId())
                .orElseThrow(() -> new RuntimeException("User not found"));
        
        existingUser.setRealName(user.getRealName());
        existingUser.setPhone(user.getPhone());
        existingUser.setAddress(user.getAddress());
        
        return userRepository.save(existingUser);
    }

    public List<User> findByRole(UserRole role) {
        try {
            logger.debug("Finding users by role: {}", role);
            List<User> users = userRepository.findByRole(role);
            logger.debug("Found {} users with role {}", users.size(), role);
            return users;
        } catch (Exception e) {
            logger.error("Error finding users by role {}: {}", role, e.getMessage(), e);
            throw new RuntimeException("获取用户列表失败：" + e.getMessage(), e);
        }
    }

    public List<User> findPendingFarmers() {
        return userRepository.findByRoleAndApproved(UserRole.FARMER, false);
    }

    @Transactional
    public User findById(Long userId) {
        return userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found with id: " + userId));
    }

    @Transactional
    public void deleteUser(Long userId) {
        logger.info("Attempting to delete user with ID: {}", userId);
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("User not found with id: " + userId));
        
        if (user.getRole() == UserRole.ADMIN) {
            logger.error("Attempt to delete admin user: {}", userId);
            throw new RuntimeException("不能删除管理员账号");
        }
        
        try {
            userRepository.delete(user);
            logger.info("Successfully deleted user with ID: {}", userId);
        } catch (Exception e) {
            logger.error("Error deleting user with ID: {}", userId, e);
            throw new RuntimeException("删除用户失败：" + e.getMessage());
        }
    }
} 